// 实习申请Service
package org.example.backend.service;

import org.example.backend.dto.InternshipApplicationDetailDto;
import org.example.backend.dto.InternshipApplicationDto;
import org.example.backend.entity.*;
import org.example.backend.exception.BusinessException;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.*;
import org.example.backend.service.InternshipService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class InternshipApplicationService {

    private final InternshipApplicationRepository internshipApplicationRepository;
    private final InternshipPositionRepository internshipPositionRepository;
    private final StudentService studentService;
    private final StudentRepository studentRepository;
    private final CompanyRepository companyRepository;
    private final InternshipRepository internshipRepository;
    private final InternshipService internshipService;

    public InternshipApplicationService(InternshipApplicationRepository internshipApplicationRepository,
                                        InternshipPositionRepository internshipPositionRepository,
                                        StudentService studentService,
                                        StudentRepository studentRepository,
                                        CompanyRepository companyRepository,
                                        InternshipRepository internshipRepository,
                                        InternshipService internshipService) {
        this.internshipApplicationRepository = internshipApplicationRepository;
        this.internshipPositionRepository = internshipPositionRepository;
        this.studentService = studentService;
        this.studentRepository = studentRepository;
        this.companyRepository = companyRepository;
        this.internshipRepository = internshipRepository;
        this.internshipService = internshipService;
    }

    /**
     * 学生提交实习申请
     */
    public InternshipApplication submitApplication(InternshipApplicationDto applicationDto, Long studentId) {
        // 检查岗位是否存在且已发布
        InternshipPosition position = internshipPositionRepository.findById(applicationDto.getPositionId())
                .orElseThrow(() -> new ResourceNotFoundException("实习岗位不存在"));

        if (position.getStatus() != 1) {
            throw new BusinessException("该岗位暂不可申请");
        }

        // 检查是否已提交过该岗位的申请
        if (internshipApplicationRepository.findByStudentIdAndPositionId(studentId, position.getId()).isPresent()) {
            throw new BusinessException("您已提交过该岗位的申请");
        }

        InternshipApplication application = new InternshipApplication();
        application.setStudentId(studentId);
        application.setPositionId(position.getId());
        application.setCompanyId(position.getCompanyId());
        application.setResumeUrl(applicationDto.getResumeUrl());
        application.setCoverLetter(applicationDto.getCoverLetter());
        application.setStatus(0); // 默认待审核状态

        return internshipApplicationRepository.save(application);
    }

    /**
     * 获取学生的所有申请记录
     */
    @Transactional(readOnly = true)
    public Page<InternshipApplication> getApplicationsByStudent(Long studentId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "appliedAt"));
        return internshipApplicationRepository.findByStudentId(studentId, pageable);
    }

    /**
     * 获取申请详情（包含关联信息）
     */
    @Transactional(readOnly = true)
    public InternshipApplicationDetailDto getApplicationWithDetails(Long applicationId) {
        InternshipApplication application = internshipApplicationRepository.findById(applicationId)
                .orElseThrow(() -> new ResourceNotFoundException("申请记录不存在"));

        return convertToDetailDto(application);
    }


    /**
     * 学生获取自己的申请列表（包含关联信息）
     */
    @Transactional(readOnly = true)
    public Page<InternshipApplicationDetailDto> getApplicationsWithDetailsByStudent(Long studentId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "appliedAt"));
        Page<InternshipApplication> applicationPage = internshipApplicationRepository.findByStudentId(studentId, pageable);

        return applicationPage.map(this::convertToDetailDto);
    }


    /**
     * 学生取消申请
     */
    public InternshipApplication cancelApplication(Long applicationId, Long studentId) {
        InternshipApplication application = internshipApplicationRepository.findById(applicationId)
                .orElseThrow(() -> new ResourceNotFoundException("申请记录不存在"));

        // 检查申请是否属于该学生
        if (!application.getStudentId().equals(studentId)) {
            throw new BusinessException("无权限操作该申请");
        }

        // 只有待审核状态的申请可以取消
        if (application.getStatus() != 0) {
            throw new BusinessException("该申请状态无法取消");
        }

        application.setStatus(3); // 设置为已取消状态
        application.setProcessedAt(new java.util.Date());
        return internshipApplicationRepository.save(application);
    }

    /**
     * 企业获取收到的申请列表（包含关联信息）
     */
    @Transactional(readOnly = true)
    public Page<InternshipApplicationDetailDto> getApplicationsWithDetailsByCompany(Long companyId, Integer status, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "appliedAt"));
        Page<InternshipApplication> applicationPage;

        if (status != null) {
            applicationPage = internshipApplicationRepository.findByCompanyIdAndStatus(companyId, status, pageable);
        } else {
            applicationPage = internshipApplicationRepository.findByCompanyId(companyId, pageable);
        }

        return applicationPage.map(this::convertToDetailDto);
    }

    /**
     * 企业处理申请（通过或拒绝）
     */
    public InternshipApplication processApplication(Long applicationId, Long companyId, Integer status, String rejectReason) {
        InternshipApplication application = internshipApplicationRepository.findById(applicationId)
                .orElseThrow(() -> new ResourceNotFoundException("申请记录不存在"));

        // 检查申请是否属于该公司
        if (!application.getCompanyId().equals(companyId)) {
            throw new BusinessException("无权限操作该申请");
        }

        // 只有待审核状态的申请可以处理
        if (application.getStatus() != 0) {
            throw new BusinessException("该申请状态无法处理");
        }

        application.setStatus(status); // 1通过 2拒绝
        if (status == 2) {
            application.setRejectReason(rejectReason);
        }
        application.setProcessedAt(new java.util.Date());

        InternshipApplication savedApplication = internshipApplicationRepository.save(application);

        // 如果申请通过，创建实习记录
        if (status == 1) {
            internshipService.createInternship(application);
        }

        return savedApplication;
    }

    /**
     * 管理员获取所有申请列表（包含关联信息）
     */
    @Transactional(readOnly = true)
    public Page<InternshipApplicationDetailDto> getAllApplicationsWithDetails(Integer status, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "appliedAt"));
        Page<InternshipApplication> applicationPage;

        if (status != null) {
            applicationPage = internshipApplicationRepository.findByStatus(status, pageable);
        } else {
            applicationPage = internshipApplicationRepository.findAll(pageable);
        }

        return applicationPage.map(this::convertToDetailDto);
    }

    /**
     * 将 InternshipApplication 转换为 InternshipApplicationDetailDto
     */
    private InternshipApplicationDetailDto convertToDetailDto(InternshipApplication application) {
        InternshipApplicationDetailDto dto = new InternshipApplicationDetailDto();
        dto.setId(application.getId());
        dto.setStudentId(application.getStudentId());
        dto.setPositionId(application.getPositionId());
        dto.setCompanyId(application.getCompanyId());
        dto.setResumeUrl(application.getResumeUrl());
        dto.setCoverLetter(application.getCoverLetter());
        dto.setStatus(application.getStatus());
        dto.setRejectReason(application.getRejectReason());
        dto.setAppliedAt(application.getAppliedAt());
        dto.setProcessedAt(application.getProcessedAt());
        dto.setCreatedAt(application.getCreatedAt());

        // 获取学生姓名
        try {
            Student student = studentRepository.findById(application.getStudentId())
                    .orElse(null);
            if (student != null) {
                dto.setStudentName(student.getName());
            }
        } catch (Exception e) {
            // 忽略异常
        }

        // 获取岗位标题
        try {
            InternshipPosition position = internshipPositionRepository.findById(application.getPositionId())
                    .orElse(null);
            if (position != null) {
                dto.setPositionTitle(position.getTitle());
            }
        } catch (Exception e) {
            // 忽略异常
        }

        // 获取公司名称
        try {
            Company company = companyRepository.findById(application.getCompanyId())
                    .orElse(null);
            if (company != null) {
                dto.setCompanyName(company.getName());
            }
        } catch (Exception e) {
            // 忽略异常
        }

        return dto;
    }

}
